package pres.seanlang.utility.android;

import android.os.Handler;
import android.os.Looper;

import pres.seanlang.utility.ThreadUtils;

/**
 *  Android系统线程工具包装
 * @author SeanLang
 */
public class AThreadUtils extends ThreadUtils {
    protected AThreadUtils() { throw new UnsupportedOperationException("can't instance..."); }

    private static final String TAG = "AThreadUtils";

    private static Handler HANDLER = null;

    synchronized private static Handler getHandler() {
        if(HANDLER == null) {
            try {
                HANDLER = new Handler(Looper.getMainLooper());
            } catch (Exception e) {
                System.err.println(TAG + " Create handler error. " + e);
            }
        }

        return HANDLER;
    }

    /**
     *  检测当前线程是否main线程
     * @return
     */
    public static boolean isMainThread() {
        return getHandler() == null ? false : (Looper.myLooper() == Looper.getMainLooper());
    }

    /**
     *  在main线程上运行task
     * @param task
     */
    public static void runOnMain(Runnable task) {
        Handler handler = getHandler();
        if(handler != null) {
            handler.post(task);
        }
    }

    /**
     *  在main线程上延时运行task
     * @param task
     * @param ms        延时时间, ms
     */
    public static void runDelayedOnMain(Runnable task, long ms) {
        Handler handler = getHandler();
        if(handler != null) {
            handler.postDelayed(task, ms);
        }
    }
}
